package org.example.filter;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.example.Contant.BusinessException;
import org.example.common.UserContextHolder;
import org.example.dto.UserDto;
import org.example.entity.User;

import org.example.util.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Optional;

@Component
public class JwtAuthenticationFilter implements Filter {


    @Resource
    private RedisTemplate<String, UserDto> redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        String token = httpServletRequest.getHeader("Authorization");
        // 1. 首先检查是否是登录页面或登录请求
        String requestURI = httpServletRequest.getRequestURI();

        if ((token == null || token.isEmpty()) && isLoginPageOrRequest(requestURI)){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        System.out.println("这里执行了吗？");
        //解析token
        String username = JwtUtil.parseToken(token);
        UserDto user = redisTemplate.opsForValue().get(username);
        if (BeanUtil.isEmpty(user)){
            throw new BusinessException("500","登录过期");
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    /**
     * 检查是否是登录页面或登录请求
     */
    private boolean isLoginPageOrRequest(String uri) {
        return uri.equals("/api/login") ||
            uri.contains("/api/register") ||
            uri.contains("/api/chat") ||
            uri.contains("/api/account") ||
            uri.contains("/favicon.ico");
    }
}
